<?php

namespace app\client\controller\course;

use app\common\controller\Frontend;
use app\common\model\banxi\core\CoreCourseAppointment;
use app\common\model\banxi\core\CoreTrialClassConfig;
use app\common\model\banxi\student\StudentCourseAppointment;
use app\common\model\banxi\student\StudentExperienceAppointment;
use app\common\model\banxi\subject\SubjectTeach;
use app\common\model\banxi\trainer\Trainer;

/*
 * 排课
 * */

class CourseAppointment extends Frontend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
    }

    /*
     * 排课记录-按月
     * */
    public function appointmentListByMonth()
    {
        $ym = $this->request->get('ym', '');

        // 优化日期处理
        $yearMonth = $ym ?: date('Y-m');
        $startDate = (new \DateTime("first day of {$yearMonth}"))->format('Y-m-d');
        $endDate = (new \DateTime("last day of {$yearMonth}"))->format('Y-m-d');

        // 生成日期数组
        $dates = [];
        $currentDate = new \DateTime($startDate);
        $endDateObj = new \DateTime($endDate);

        while ($currentDate <= $endDateObj) {
            $dates[] = $currentDate->format('Y-m-d');
            $currentDate->modify('+1 day');
        }

        $studentId = $this->auth->id;

        // 一次性查询当月所有预约数据
        $monthlyAppointments = CoreCourseAppointment::where('studentId', $studentId)
            ->whereBetween('date', [$startDate, $endDate])
            ->group('date')
            ->field('date, COUNT(*) as count')
            ->select();

        $appointmentMap = [];
        foreach ($monthlyAppointments as $appointment) {
            $appointmentMap[$appointment['date']] = $appointment['count'];
        }

        // 构建结果
        $result = [];
        foreach ($dates as $date) {
            $result[] = [
                'date' => $date,
                'count' => $appointmentMap[$date] ?? 0
            ];
        }

        $this->ok('操作成功', $result);
    }


    /*
     * 排课记录-按日
     * */
    public function appointmentListByDay()
    {
        $param = $this->request->get(['index', 'limit', 'date' => '']);

        $date = $param['date'];
        if (!$date) {
            $date = date('Y-m-d');
        }
        $pageParams = get_page_params($param);
        $studentId = $this->auth->id;
        // 查询当天的排课记录
        $list = CoreCourseAppointment::with([
            'trainerInfo' => function ($query) {
                $query->field('id,name,avatar');
            }, 'skRecordInfo' => function ($query) {
                $query->field('id,appointmentId');
            }])->where(['date' => $date, 'studentId' => $studentId])
            ->orderRaw("FIELD(appointmentStatus, 2, 1, 4, 3, 5)")
            ->order(['startTime' => 'asc'])
            ->field('id,courseName,startTime,appointmentStatus,courseFullType,trainerId')
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ]);

        $this->ok('操作成功', $list);
    }


    /*
     * 排课记录-按状态(今天)
     */
    public function appointmentListByStatus()
    {
        $param = $this->request->get(['date' => '', 'status' => '']);
        $studentId = $this->auth->id;
        $query = [
            'query' => [
                'EQ_studentId' => $studentId
            ]
        ];
        $date = $param['date'];
        if (empty($date)) {
            $date = date('Y-m-d');
        }
        $query['query']['EQ_date'] = $date;

        if (!empty($param['status'])) {
            if (!in_array($param['status'], [1, 2, 3, 4, 5])) {
                $this->fail('请选择正确的课程状态');
            }
            $query['query']['EQ_appointmentStatus'] = $param['status'];
        }
        $where =get_query($query);

        // 查询当天的排课记录
        $todayList = CoreCourseAppointment::where($where)
            ->order(['date' => 'desc', 'startTime' => 'asc'])
            ->field('id,courseName,date,startTime,endTime,appointmentStatus,courseFullType')
            ->select();
        $this->ok('操作成功', $todayList);
    }

    /*
     * 排课记录-按状态(往期)
     */
    public function appointmentListByBefore()
    {
        $param = $this->request->get(['index', 'limit', 'status']);
        $studentId = $this->auth->id;
        $date = date('Y-m-d');
        $query = [
            'query' => [
                'EQ_studentId' => $studentId,
                'LT_date' => $date,
            ]
        ];
        if (!empty($param['status'])) {
            if (!in_array($param['status'], [1, 2, 3, 4, 5])) {
                $this->fail('请选择正确的课程状态');
            }
            $query['query']['EQ_appointmentStatus'] = $param['status'];
        }
        $where = get_query($query);
        //往期
        $previousPeriodList = CoreCourseAppointment::where($where)
            ->order(['date' => 'desc', 'startTime' => 'asc'])
            ->field('id,courseName,date,startTime,endTime,appointmentStatus,courseFullType')
            ->select();
        $this->ok('操作成功', $previousPeriodList);
    }


    /*
     * 提交预约
     * */
    public function submitAppointment()
    {
        $time = $this->request->post('time', '');
        $trainerId = $this->request->post('trainerId', 0);
        $courseFullType = $this->request->post('courseFullType', '');
        $courseId = $this->request->post('courseId', 0);

        if (!in_array($courseFullType, [1, 2])) {
            $this->fail('课时类型错误');
        }
        $TrainerModel = new Trainer();
        $trainerInfo = $TrainerModel->where(['id' => $trainerId])->find();
        if (!$trainerInfo) {
            $this->fail('老师不存在');
        }
        $SubjectTeachcModel = new SubjectTeach();
        $subjectTeachInfo = $SubjectTeachcModel->where(['id' => $courseId, 'status' => 1])->find();
        if (!$subjectTeachInfo) {
            $this->fail('课程不存在');
        }

        //验证老师是否可预约（预约时间是否冲突）
        $CoreCourseAppointmentModel = new CoreCourseAppointment();
        // 解析传入的时间参数
        $timestamp = strtotime($time);
        $date = date('Y-m-d', $timestamp);
        $startTime = date('H:i:s', $timestamp);
        $addSeconds = $courseFullType * 1800;//根据课时类型计算时长
        $endTime = date('H:i:s', strtotime("+$addSeconds seconds", $timestamp));
        // 查询该教师在该日期的所有预约
        $existingAppointments = $CoreCourseAppointmentModel->where([
            'trainerId' => $trainerId,
            'date' => $date
        ])->where('appointmentStatus', '<>', 3)->select();
        $student = $this->auth->getUserInfo();

        // 检查时间是否冲突
        foreach ($existingAppointments as $appointment) {
            // 检查时间是否冲突
            // 冲突条件：要预约的时间在现有预约时间段内，或者现有预约时间在要预约的时间段内
            if (($startTime >= $appointment['startTime'] && $startTime < $appointment['endTime'])) {
                $this->fail('该时间段已被预约，请选择其他时间');
            }
        }

        //创建预约
        $StudentCourseAppointmentModel = new StudentCourseAppointment();
        $data = [
            'studentId' => $student['id'],
            'studentOrganizationId' => $student['organizationId'],
            'trainerId' => $trainerId,
            'courseId' => $courseId,
            'courseName' => $subjectTeachInfo['name'],
            'courseFullType' => $courseFullType,
            'courseDeliveryType' => 1,
            'date' => $date,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'courseType' => 2,
            'appointmentStatus' => 1
        ];

        $StudentCourseAppointmentModel->save($data);

        $this->ok('操作成功');
    }

    /*
     * 体验预约配置
     * */
    public function experienceAppointmentConfig()
    {
        $CoreTrialClassConfigModel = new CoreTrialClassConfig();
        $trialClassConfigInfo = $CoreTrialClassConfigModel->where(['id' => 1])->find();
        $this->ok('操作成功', $trialClassConfigInfo);
    }

    /*
     * 提交体验预约
     * */
    public function submitExperienceAppointment()
    {
        $time = $this->request->post('time', '');
        $courseId = $this->request->post('courseId', 0);

        $SubjectTeachcModel = new SubjectTeach();
        $subjectTeachInfo = $SubjectTeachcModel->where(['id' => $courseId, 'status' => 1])->find();
        if (!$subjectTeachInfo) {
            $this->fail('课程不存在');
        }

        // 解析传入的时间参数
        $timestamp = strtotime($time);
        $date = date('Y-m-d', $timestamp);
        $startTime = date('H:i:s', $timestamp);
        $addSeconds = 2 * 1800;//根据课时类型计算时长
        $endTime = date('H:i:s', strtotime("+$addSeconds seconds", $timestamp));

        $student = $this->auth->getUserInfo();

        //体验课配置信息
        $CoreTrialClassConfigModel = new CoreTrialClassConfig();
        $trialClassConfigInfo = $CoreTrialClassConfigModel->where(['id' => 1])->find();
        //创建体验预约
        $StudentExperienceAppointmentModel = new StudentExperienceAppointment();
        $orderSn = buildNo('EA');
        $data = [
            'orderSn' => $orderSn,
            'price' => $trialClassConfigInfo['price'],
            'payPrice' => $trialClassConfigInfo['price'],
            'payType' => 'ali',
            'payTime' => date('Y-m-d H:i:s'),
            'studentId' => $student['id'],
            'studentOrganizationId' => $student['organizationId'],
            'courseId' => $courseId,
            'courseName' => $subjectTeachInfo['name'],
            'courseFullType' => 3,
            'courseDeliveryType' => 1,
            'date' => $date,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'courseType' => 2,
            'orderStatus' => 2
        ];
        //        halt($data);
        $StudentExperienceAppointmentModel->create($data);

        $this->ok('操作成功');
    }
}